package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 设备数据 Service 实现类
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

    @Autowired
    private DeviceMapper deviceMapper;

    /*
     * 处理MQ接收到数据后传递的处理方法
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(device==null){
            log.error("设备不存在");
            return;
        }
        //存在则继续
        iotMsgNotifyData.getBody().getServices().forEach(s->{
            Map<String, Object> properties = s.getProperties();
            if(ObjectUtil.isEmpty( properties)){
                //没有修改属性
                return;
            }
            //处理上报的数据——时间
            LocalDateTime eventTime = LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //不为空则处理接收到的属性数据
            List<DeviceData> deviceDataList = new ArrayList<>();
            properties.forEach((key,value)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(alarmTime)
                        .dataValue(value + "")
                        .build();
                deviceDataList.add(deviceData);
            });
            saveBatch(deviceDataList);
        });
    }

    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto){
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        Page<DeviceData> page=new Page<>(dto.getPageNum(),dto.getPageSize());

        //模糊查询设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
            queryWrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        //精确查询功能名称
        if(StringUtils.isNotEmpty(dto.getFunctionId())){
            queryWrapper.eq(DeviceData::getFunctionId,dto.getFunctionId());
        }
        //时间范围查询
        if(ObjectUtils.isNotEmpty(dto.getStartTime())&&ObjectUtils.isNotEmpty(dto.getEndTime())){
            queryWrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }

        //分页查询
        page=page(page,queryWrapper);

        //封装分页对象
        return getTableDataInfo(page);

    }

    /**
     * 封装分页对象
     * @param page
     * @return
     */
    @NotNull
    private static TableDataInfo getTableDataInfo(Page<DeviceData> page){
        TableDataInfo tableData=new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
}